
import sys

if __name__=="__main__":
    if len(sys.argv)<=3:
        print "Usage: python %s STRANDED_JUNCTION_FILE JUNCTION_FILE TRIM_SIZE" % sys.argv[0]
        sys.exit(1)
    strandedJunctionFile = sys.argv[1]
    junctionFile = sys.argv[2]
    trimSize = int(sys.argv[3])
    strands = {}
    for line in open(strandedJunctionFile):
        if line.startswith(">"):
            id = line.strip()
            (name, loc) = tuple(id.split(":"))
            (chr, strand, leftWidth, rightWidth, leftLoc, rightLoc) = tuple(loc.split("_"))
        strands[(chr, leftLoc, rightLoc)] = (strand, name)
    print >> sys.stderr, "# Read strand info for %d junctions from %s" % (len(strands), strandedJunctionFile)
    byId = {}
    for line in open(junctionFile):
        if line.startswith(">"):
            id = line.strip()
            fields = id.split("_")
            (leftWidth, rightWidth, chr, leftLoc, rightLoc) = tuple(fields[-5:])
            chr = "chr" + chr
            (strand, name) = strands[(chr, leftLoc, rightLoc)]
            (index, geneName) = tuple(name.split("_"))
            index = int(index[1:])
            leftWidth = int(leftWidth)
            rightWidth = int(rightWidth)
            newLeftWidth = min(trimSize, leftWidth)
            newRightWidth = min(trimSize, rightWidth)
            leftTrim = leftWidth - newLeftWidth
            rightTrim = rightWidth - newRightWidth
            newId = "%s:%s_%s_%d_%d_%s_%s" % (name, chr, strand, newLeftWidth, newRightWidth, leftLoc, rightLoc)
        else:
            seq = line.strip()
            if len(seq) != leftWidth+rightWidth:
                print >> sys.stderr, "# Warning: seq length appears wrong for", id, "=", seq
            byId[index] = (newId, seq[leftTrim:len(seq)-rightTrim])
            if len(byId[index][1]) != newLeftWidth+newRightWidth:
                raise Exception("trouble")
    indexKeys = byId.keys()
    indexKeys.sort()
    for index in indexKeys:
        print byId[index][0]
        print byId[index][1]

